<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- BIM考核记录编辑 -->
    <a-form-model
      id="base-breadcrumb"
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      style="position: relative"
    >
      <a-spin :spinning="loading">
        <!-- 基本信息 -->
        <a-card :bordered="false">
          <title-name title="基本信息" />
          <custom-form
            :is-emit="false"
            :form-list="formList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
            :form-components="$refs"
          >
            <!-- 被考核单位 -->
            <template #unitProjectList>
              <a-table
                bordered
                :scroll="{ y: 500 }"
                :loading="loadingTable"
                :dataSource="form.unitProjectList || []"
                :pagination="false"
                rowKey="unitId"
                :columns="[
                  {
                    dataIndex: 'index',
                    width: '10%',
                    title: '序号',
                    customRender: (text, record, index) => Number(index) + 1
                  },
                  { dataIndex: 'unitName', width: '50%', title: '被考核单位' },
                  { dataIndex: 'score', width: '40%', title: '得分', scopedSlots: { customRender: 'score' } }
                ]"
              >
                <!-- 得分 -->
                <div class="requiredFormItem" slot="score" slot-scope="text, record">
                  <BaseInputNumber
                    placeholder="请输入考核得分"
                    :precision="2"
                    :min="0"
                    v-model="record.score"
                    @change="handleCheck(record)"
                  />
                  <span v-if="record.isEmpty" class="del_btn">请输入考核得分</span>
                </div>
              </a-table>
            </template>
          </custom-form>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top">
          <a-button v-if="editModel != 0" :loading="loading" type="primary" class="button_right" @click="handleSubmit">
            提交
          </a-button>
          <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose"> 关闭 </a-button>
        </div>
      </a-spin>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import {
  insertBimInspectRecord,
  updateBimInspectRecord,
  getBimInspectRecordById,
  getPageTypesLabel
} from '@/api/bimIntegrate/bimResource.js'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Selector from '@/components/Select/Selector'
import { getAllBranchCompany } from '@/api/commons'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
import template from '@/views/construction/gantt/template.vue'

export default {
  components: { template },
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  data() {
    return {
      loading: false, // 提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      id: '', // 业务id
      form: {}, // 表单
      rules: {
        inspectType: [{ required: true, message: '请选择考核分类', trigger: 'change' }],
        inspectNameId: [{ required: true, message: '请选择考核名称', trigger: 'change' }],
        inspectLevel: [{ required: true, message: '请选择考核层级', trigger: 'change' }],
        inspectMonth: [{ required: true, message: '请选择考核月度', trigger: 'change' }],
        inspectPeriod: [{ required: true, message: '请输入考核期数', trigger: 'change' }],
        unitProjectList: [{ type: 'array', required: true, message: '被考核单位不能为空', trigger: 'change' }]
      },
      loadingTable: false, //表格loading
      branchCompanys: [], // 分公司列表
      projects: [] // 项目列表
    }
  },
  mounted() {
    this.$route.meta.title = ['考核记录查看', '考核记录编辑', '考核记录新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      getBimInspectRecordById({
        id: this.id
      })
        .then((res) => {
          this.loading = false
          this.form = res.data
        })
        .catch(() => {
          this.loading = false
        })
    }
  },
  computed: {
    // 表单列表
    formList() {
      return [
        {
          keyName: 'inspectType',
          type: 'a-select',
          label: '考核分类',
          data: [
            {
              label: '信息化',
              value: 0
            },
            {
              label: 'BIM',
              value: 1
            }
          ],
          customRender(e) {
            return ['信息化', 'BIM'][e] || '无'
          }
        },
        {
          keyName: 'inspectNameId',
          viewName: 'inspectName',
          type: Selector,
          label: '考核名称',
          attrs: {
            customApi: getPageTypesLabel,
            customQuery: { param: { type: '32' } },
            dataValue: 'data.list'
          }
        },
        {
          keyName: 'inspectMonth',
          type: 'a-month-picker',
          label: '考核月度',
          attrs: {
            valueFormat: 'YYYY-MM'
          }
        },
        {
          keyName: 'inspectPeriod',
          type: 'BaseInputNumber',
          label: '考核期数',
          precision: 0,
          attrs: {
            min: 1
          }
        },
        {
          keyName: 'inspectLevel',
          type: 'a-select',
          label: '考核层级',
          data: [
            {
              label: '分公司',
              value: 0
            },
            {
              label: '项目',
              value: 1
            }
          ],
          customRender(e) {
            return ['分公司', '项目'][e] || '无'
          },
          change: (e) => {
            // 若层级为分公司，且分公司列表为空，则请求分公司列表
            if (e === 0) {
              if (this.branchCompanys.length === 0) {
                this.loadingTable = true
                getAllBranchCompany({ tagCodes: ['BC'] })
                  .then((res) => {
                    this.loadingTable = false
                    if (res?.data?.length > 0) {
                      // 转义单位名称和组织架构id
                      let list = res.data.map((item) => ({
                        unitName: item.name,
                        unitId: item.id
                      }))
                      this.branchCompanys = this.$clone(list)
                      this.$set(this.form, 'unitProjectList', list)
                    }
                  })
                  .catch(() => {
                    this.loadingTable = false
                  })
              } else {
                this.form.unitProjectList = this.branchCompanys
              }
              // 若层级为项目，且项目列表为空，则请求项目列表
            } else if (e === 1) {
              if (this.projects.length === 0) {
                this.loadingTable = true
                let args = { branchComIds: [] }
                this.$currentPost().code === 'BC' && args.branchComIds.push(this.$currentPost().id)
                getAuditProject(args)
                  .then((res) => {
                    this.loadingTable = false
                    if (res?.code === 200) {
                      // 转义单位名称和组织架构id
                      let list = res.data.map((item) => ({
                        unitName: item.projectName,
                        unitId: item.projectDeptId,
                        keyProject: item.keyProject
                      }))
                      this.projects = this.$clone(list)
                      this.$set(this.form, 'unitProjectList', list)
                    }
                  })
                  .catch(() => {
                    this.loadingTable = false
                  })
              } else {
                this.form.unitProjectList = this.projects
              }
            } else {
              // 清空列表
              this.$set(this.form, 'unitProjectList', [])
            }
          }
        },
        {
          keyName: 'unitProjectList',
          span: 24,
          slot: true,
          label: '被考核单位'
        },
        {
          keyName: 'remark',
          type: 'BaseTextarea',
          label: '备注',
          span: 24
        },
        {
          keyName: 'fileInfoList',
          type: 'uploadFile',
          label: '附件',
          span: 24,
          businessCode: 'BIM06'
        }
      ]
    }
  },
  methods: {
    /**
     * @description: 校验得分
     * @param {*} record：行对象
     */
    handleCheck(record) {
      record.isEmpty = !record.score && record.score !== 0
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      let url = [updateBimInspectRecord, insertBimInspectRecord][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 校验考核得分
          for (let index in this.form.unitProjectList) {
            let record = this.form.unitProjectList[index]
            this.$set(this.form.unitProjectList[index], 'isEmpty', !record.score && record.score !== 0)
            record.isEmpty && this.$message.warning(`第${Number(index) + 1}行${record.unitName}考核得分未填写`)
          }
          if (this.form.unitProjectList.some((item) => item.isEmpty)) {
            return
          }
          // 提交表单
          that.loading = true
          let form = that.$clone(that.form)
          url(form)
            .then((res) => {
              that.loading = false
              if (res.code === '0' || res.data.code === '0') {
                that.$message.success('提交成功！')
                that.$multiTab.close()
              }
            })
            .catch((res) => {
              that.loading = false
            })
        }
      })
    }
  }
}
</script>